using System;
using System.Collections.Generic;
using System.Text;
using SharksHunter.TransferObjects.Model;
using System.IO;

namespace SharksHunter.Engine.CSV
{
    public class CSVScanner : SharksHunter.Service.Interfaces.IScanner<ItemTO>
    {
        private string _body;
        public CSVScanner(string fpath)
        {
            using(StreamReader sr = File.OpenText(fpath))
            {
                _body = sr.ReadToEnd();
                sr.Close();
            }
        }

        public IEnumerable<ItemTO> Scan()
        {
            long size,crc;
            string name = "", shot = "";

            ItemTO newitem = null;

            string[] stritems = _body.Split('\n', '\r');
            foreach(string stritem in stritems)
            {
                if(stritem == "")
                    continue;//because of '\n', '\r' we get empty lines
                
                string[] fields = stritem.Split(',');
                name = fields[0];
                size = long.Parse(fields[1]);
                crc = long.Parse(fields[2],System.Globalization.NumberStyles.HexNumber);

                newitem = new ItemTO();
                newitem.Name = name;
                newitem.Size = size;
                newitem.CRC32 = crc;

                if (fields.Length >= 4)
                {
                    shot = "";
                    for(int i = 3; i < fields.Length ;++i) 
                    {
                        if(fields[i] == "")
                            continue;//ignore empty fields
                        shot += fields[i].ToString() + ",";
                    }
                    if(shot.EndsWith(","))
                        shot = shot.Substring(0, shot.Length-1);

                    newitem.Shot = shot;
                }
                else
                    throw new Exception.NotValidCSVFileException(_body);

                yield return newitem; 
            }
        }
    }
}
